#!/bin/bash

VERSION=6.2.14
PASSWORD='redis@2024'
REDIS_DIR=/opt/redis
REDIS_CONF_DIR=$REDIS_DIR/etc
REDIS_DATA_DIR=$REDIS_DIR/data
REDIS_BIN_DIR=$REDIS_DIR/bin

# 颜色代码
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # 无颜色

# 打印带颜色的消息
function echo_colored() {
    echo -e "${2}${1}${NC}"
}

# 检查是否以root身份运行
if [ "$EUID" -ne 0 ]; then
    echo_colored "请使用root权限运行此脚本" $RED
    exit 1
fi

# 安装必要的软件包
echo_colored "安装必要的软件包..." $YELLOW
if yum -y install gcc gcc-c++ > /dev/null; then
    echo_colored "依赖包安装成功。" $GREEN
else
    echo_colored "依赖包安装失败。" $RED
    exit 1
fi

# 下载Redis源码包
echo_colored "下载Redis-${VERSION}..." $YELLOW
if wget http://download.redis.io/releases/redis-${VERSION}.tar.gz; then
    echo_colored "Redis-${VERSION}下载成功。" $GREEN
else
    echo_colored "Redis-${VERSION}下载失败。" $RED
    exit 1
fi

# 解压并编译安装Redis
echo_colored "解压并编译安装Redis..." $YELLOW
if tar -zxvf redis-${VERSION}.tar.gz && cd redis-${VERSION}; then
    if make MALLOC=libc CFLAGS="-march=x86-64" && make PREFIX=$REDIS_DIR install; then
        echo_colored "Redis编译安装成功。" $GREEN
    else
        echo_colored "Redis编译安装失败。" $RED
        exit 1
    fi
else
    echo_colored "解压Redis-${VERSION}失败。" $RED
    exit 1
fi

# 创建目录并复制配置文件
echo_colored "配置Redis..." $YELLOW
mkdir -p $REDIS_CONF_DIR $REDIS_DATA_DIR
cp ./redis.conf $REDIS_CONF_DIR/

# 修改配置文件
sed -i 's|^daemonize.*|daemonize yes|' $REDIS_CONF_DIR/redis.conf
sed -i "s/^bind 127.0.0.1 -::1/bind 0.0.0.0/" $REDIS_CONF_DIR/redis.conf
sed -i "s/^# requirepass foobared/requirepass $PASSWORD/" $REDIS_CONF_DIR/redis.conf
sed -i 's|^dir ./|dir /opt/redis/data|' $REDIS_CONF_DIR/redis.conf

# 启动Redis服务器
echo_colored "启动Redis服务器..." $YELLOW
if $REDIS_BIN_DIR/redis-server $REDIS_CONF_DIR/redis.conf; then
    echo_colored "Redis服务器启动成功。" $GREEN
else
    echo_colored "Redis服务器启动失败。" $RED
    exit 1
fi

# 下载并设置redis-control脚本
echo_colored "设置redis-control脚本..." $YELLOW
if wget https://gitee.com/michelalive/Deploy-repo/raw/master/middle/redis/redis-control.sh; then
    chmod a+x redis-control.sh && mv redis-control.sh /usr/local/bin
    echo_colored "redis-control脚本设置成功。" $GREEN
else
    echo_colored "下载redis-control脚本失败。" $RED
    exit 1
fi

echo_colored "Redis ${VERSION} 安装成功！密码是 '${PASSWORD}'" $GREEN
echo_colored "使用以下命令管理redis:" $YELLOW
echo_colored "redis-control.sh start" $YELLOW
echo_colored "redis-control.sh stop REDIS_PASSWORD 或 pkill redis" $YELLOW
echo_colored "redis-control.sh restart" $YELLOW
